/**
 * Adapter danh sach cac bai hat Online
 */
package com.toidep.adapters;

import java.util.ArrayList;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.toidep.R;
import com.toidep.activities.MainActivity;
import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.base.BaseFragment;
import com.toidep.bitmaputil.ImageWorker;
import com.toidep.config.ConfigUtility;
import com.toidep.entities.AlbumEntity;
import com.toidep.entities.ArticleEntity;
import com.toidep.entities.UpdateEntity;
import com.toidep.entities.VideoEntity;
import com.toidep.interfaces.ResponseListener;
import com.toidep.widgets.sectionlist.AmazingAdapter;

public class UpdateAdapter extends AmazingAdapter{

	private MainActivity mainActivity;
	private BaseFragment parentFragment;
	
	private ArrayList<UpdateEntity> listData;
	public ArrayList<ViewHolder> arrViewHolder;			// QUan ly cac ViewHolder
	private ArrayList<ArticleEntity> listArticle;

	/**
	 * Constructor 
	 * Khoi tao Adapter lay danh sach Update
	 * @param ff
	 */
	public UpdateAdapter(BaseFragment ff) {
		this.mainActivity = (MainActivity) ff.getActivity();
		this.parentFragment = ff;
		this.listData = new ArrayList<UpdateEntity>();
		this.arrViewHolder = new ArrayList<ViewHolder>();
		this.listArticle = new ArrayList<ArticleEntity>();
	}
	
	public ArrayList<UpdateEntity> getListModel() {
		return this.listData;
	}
	
	public void resetList(ArrayList<UpdateEntity> l) {
		if (listData == null) {
			listData = new ArrayList<UpdateEntity>();
		}
		
		if (listArticle == null) {
			listArticle = new ArrayList<ArticleEntity>();
		}
		//===== Tao Mang ViewHolder=====
		if (arrViewHolder == null) {
			arrViewHolder = new ArrayList<ViewHolder>();
		}
		arrViewHolder.clear();
		for (int i = 0; i < l.size(); i++) {
			arrViewHolder.add(null);
		}
		//==============================
		listData.clear();
		listData.addAll(l);
		filterArticle();
		notifyDataSetChanged();
	}
	
	public void resetList() {
		if (listData == null) {
			listData = new ArrayList<UpdateEntity>();
		}
		if (arrViewHolder == null) {
			arrViewHolder = new ArrayList<ViewHolder>();
		}
		
		if (listArticle == null) {
			listArticle = new ArrayList<ArticleEntity>();
		}
		listData.clear();
		
		getFirstPage();
	}
	
	public int getCount() {
		if (listData != null)
			return listData.size();
		else 
			return 0;
	}

	public UpdateEntity getItem(int position) {
		return listData.get(position);
	}

	public long getItemId(int position) {
		return position;
	}
	
	// TODO: onNextPageRequested
	@Override
	protected void onNextPageRequested(int page) {
		getData(page);
	}

	@Override
	protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
		// do nothing
	}
	
	private class ViewHolder {
		public ImageView image;
		public RelativeLayout layoutArticle, layoutAlbum, layoutVideo;
		public TextView textviewTitle;
		public TextView textDuration, textGalleryCount;
		public TextView textName, textViewCount, textCommentCount,txtModelName;
	}

	@Override
	public View getAmazingView(int position, View convertView, ViewGroup parent) {
		final ViewHolder viewHolder;
		
		int widthImage = 0, heightImage = 0;
		int widthImageView = 0, heightImageView = 0;
		
		final UpdateEntity currentItem = getItem(position);
		
		int itemType = currentItem.getFreeType();
		if (itemType == currentItem.FREE_TYPE_ALBUM) {
			if (currentItem.getAlbumEntity().getDisplay().equals("horizontal")) {
				widthImage = ConfigUtility.size_full_width;
				heightImage = (int) (widthImage * ConfigUtility.scale_size_list_horizontal);
				
				widthImageView = ConfigUtility.scrWidth;
				heightImageView = (int) (widthImageView * ConfigUtility.scale_size_list_horizontal);
			} else {
				widthImage = ConfigUtility.size_full_width;
				heightImage = (int) (widthImage * ConfigUtility.scale_size_list_vertical);
				
				widthImageView = ConfigUtility.scrWidth;
				heightImageView = (int) (widthImageView * ConfigUtility.scale_size_list_vertical);
			}
		} else if (itemType == currentItem.FREE_TYPE_VIDEO) {
			widthImage = ConfigUtility.size_full_width;
			heightImage = (int) (widthImage * ConfigUtility.scale_size_list_horizontal);
			
			widthImageView = ConfigUtility.scrWidth;
			heightImageView = (int) (widthImageView * ConfigUtility.scale_size_list_horizontal);
		} else if ( itemType == currentItem.FREE_TYPE_NEWS  ||
					itemType == currentItem.FREE_TYPE_STORY ||
					itemType == currentItem.FREE_TYPE_EVENT    ) {
			widthImage = ConfigUtility.size_half_width;
			heightImage = (int) (widthImage*ConfigUtility.scale_size_horizontal_thumbs_item);

			widthImageView = (int) (ConfigUtility.scrWidth*ConfigUtility.scale_thumbs_news_width);
			heightImageView = (int) (widthImageView*ConfigUtility.scale_size_horizontal_thumbs_item);
		}

		if (convertView == null) {
			convertView = mainActivity.getLayoutInflater().inflate(R.layout.layout_itemlist_update, null);
			viewHolder = new ViewHolder();
			viewHolder.layoutArticle = (RelativeLayout) convertView.findViewById(R.id.layoutArticle);
			viewHolder.layoutAlbum = (RelativeLayout) convertView.findViewById(R.id.layoutAlbum);
			viewHolder.layoutVideo = (RelativeLayout) convertView.findViewById(R.id.layoutVideo);
//			viewHolder.txtModelName = (TextView) convertView.findViewById(R.id.txvModelName);
			
			if (itemType == currentItem.FREE_TYPE_ALBUM) {
				viewHolder.image = (ImageView) viewHolder.layoutAlbum.findViewById(R.id.imageView);
				viewHolder.textGalleryCount = (TextView) viewHolder.layoutAlbum.findViewById(R.id.textGalleryCount);
				viewHolder.textName = (TextView) viewHolder.layoutAlbum.findViewById(R.id.textName);
				viewHolder.txtModelName = (TextView) viewHolder.layoutAlbum.findViewById(R.id.textModelName);
				viewHolder.textViewCount = (TextView) viewHolder.layoutAlbum.findViewById(R.id.textViewCount);
				viewHolder.textCommentCount = (TextView) viewHolder.layoutAlbum.findViewById(R.id.textCommentCount);
			} else if (itemType == currentItem.FREE_TYPE_VIDEO) {
				viewHolder.image = (ImageView) viewHolder.layoutVideo.findViewById(R.id.imageView);
				viewHolder.textDuration = (TextView) viewHolder.layoutVideo.findViewById(R.id.textDuration);
				viewHolder.textName = (TextView) viewHolder.layoutVideo.findViewById(R.id.textName);
				viewHolder.txtModelName = (TextView) viewHolder.layoutVideo.findViewById(R.id.textModelName);
				viewHolder.textViewCount = (TextView) viewHolder.layoutVideo.findViewById(R.id.textViewCount);
				viewHolder.textCommentCount = (TextView) viewHolder.layoutVideo.findViewById(R.id.textCommentCount);
			} else if ( itemType == currentItem.FREE_TYPE_NEWS  ||
					itemType == currentItem.FREE_TYPE_STORY ||
					itemType == currentItem.FREE_TYPE_EVENT    ) {
				viewHolder.image = (ImageView) viewHolder.layoutArticle.findViewById(R.id.imageView);
				viewHolder.textviewTitle = (TextView) viewHolder.layoutArticle.findViewById(R.id.textviewTitle);
			}
			
			FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(widthImageView, heightImageView);
			viewHolder.image.setLayoutParams(layoutParams);
			viewHolder.image.setScaleType(ScaleType.FIT_CENTER);
			
			convertView.setTag(viewHolder);
			
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
			
			if (itemType == currentItem.FREE_TYPE_ALBUM) {
				viewHolder.image = (ImageView) viewHolder.layoutAlbum.findViewById(R.id.imageView);
				viewHolder.textGalleryCount = (TextView) viewHolder.layoutAlbum.findViewById(R.id.textGalleryCount);
				viewHolder.textName = (TextView) viewHolder.layoutAlbum.findViewById(R.id.textName);
				viewHolder.txtModelName = (TextView) viewHolder.layoutAlbum.findViewById(R.id.textModelName);
				viewHolder.textViewCount = (TextView) viewHolder.layoutAlbum.findViewById(R.id.textViewCount);
				viewHolder.textCommentCount = (TextView) viewHolder.layoutAlbum.findViewById(R.id.textCommentCount);
			} else if (itemType == currentItem.FREE_TYPE_VIDEO) {
				viewHolder.image = (ImageView) viewHolder.layoutVideo.findViewById(R.id.imageView);
				viewHolder.textDuration = (TextView) viewHolder.layoutVideo.findViewById(R.id.textDuration);
				viewHolder.textName = (TextView) viewHolder.layoutVideo.findViewById(R.id.textName);
				viewHolder.txtModelName = (TextView) viewHolder.layoutVideo.findViewById(R.id.textModelName);
				viewHolder.textViewCount = (TextView) viewHolder.layoutVideo.findViewById(R.id.textViewCount);
				viewHolder.textCommentCount = (TextView) viewHolder.layoutVideo.findViewById(R.id.textCommentCount);
			} else if ( itemType == currentItem.FREE_TYPE_NEWS  ||
					itemType == currentItem.FREE_TYPE_STORY ||
					itemType == currentItem.FREE_TYPE_EVENT    ) {
				viewHolder.image = (ImageView) viewHolder.layoutArticle.findViewById(R.id.imageView);
				viewHolder.textviewTitle = (TextView) viewHolder.layoutArticle.findViewById(R.id.textviewTitle);
			}
			
			FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(widthImageView, heightImageView);
			viewHolder.image.setLayoutParams(layoutParams);
			viewHolder.image.setScaleType(ScaleType.FIT_CENTER);
		}
		
		if (itemType == currentItem.FREE_TYPE_ALBUM) {
			viewHolder.layoutArticle.setVisibility(View.GONE);
			viewHolder.layoutAlbum.setVisibility(View.VISIBLE);
			viewHolder.layoutVideo.setVisibility(View.GONE);
			
			// Load image
			viewHolder.image.setTag(currentItem.getAlbumEntity().getThumbs());
			mainActivity.loadImage(viewHolder.image, currentItem.getAlbumEntity().getThumbs(),
					widthImage, heightImage, widthImageView, heightImageView);
			
			viewHolder.textGalleryCount.setText(currentItem.getAlbumEntity().getTotalGallery());
			viewHolder.textName.setText(currentItem.getAlbumEntity().getName() + " của");
			viewHolder.txtModelName.setText( "["+currentItem.getAlbumEntity().getModelName()+"]");
			viewHolder.textViewCount.setText(currentItem.getAlbumEntity().getTotalView());
			viewHolder.textCommentCount.setText(currentItem.getAlbumEntity().getTotalComment());
		} else if (itemType == currentItem.FREE_TYPE_VIDEO) {
			viewHolder.layoutArticle.setVisibility(View.GONE);
			viewHolder.layoutAlbum.setVisibility(View.GONE);
			viewHolder.layoutVideo.setVisibility(View.VISIBLE);
			
			// Load image
			viewHolder.image.setTag(currentItem.getVideoEntity().getThumb());
			mainActivity.loadImage(viewHolder.image, currentItem.getVideoEntity().getThumb(),
					widthImage, heightImage, widthImageView, heightImageView);
			
			viewHolder.textDuration.setText(currentItem.getVideoEntity().getDuration());
			viewHolder.textName.setText(currentItem.getVideoEntity().getTitle() + " của");
			viewHolder.txtModelName.setText( "["+currentItem.getVideoEntity().getModelName()+"]");
			viewHolder.textViewCount.setText(currentItem.getVideoEntity().getTotalView());
			viewHolder.textCommentCount.setText(currentItem.getVideoEntity().getTotalComment());
		} else if ( itemType == currentItem.FREE_TYPE_NEWS  ||
				itemType == currentItem.FREE_TYPE_STORY ||
				itemType == currentItem.FREE_TYPE_EVENT    ) {
			viewHolder.layoutArticle.setVisibility(View.VISIBLE);
			viewHolder.layoutAlbum.setVisibility(View.GONE);
			viewHolder.layoutVideo.setVisibility(View.GONE);
			
			// Load image
			viewHolder.image.setTag(currentItem.getArticleEntity().getImageUrl());
			mainActivity.loadImage(viewHolder.image, currentItem.getArticleEntity().getImageUrl(),
					widthImage, heightImage, widthImageView, heightImageView);
			
			viewHolder.textviewTitle.setText(currentItem.getArticleEntity().getIntroText());
		}
			
		return convertView;
	}

	@Override
	public void configurePinnedHeader(View header, int position, int alpha) {
		
	}

	@Override
	public int getPositionForSection(int section) {
		return 0;
	}

	@Override
	public int getSectionForPosition(int position) {
		return 0;
	}

	@Override
	public int getSectionPosition(int position) {
		return 0;
	}

	@Override
	public Object[] getSections() {
		return null;
	}
	
	/**
	 * Clear Adapter ve null
	 */
	public void clear() {
		resetPage();
		listData.clear();
		listArticle.clear();
//		listSong = null;
		clearTemporarity();
		notifyDataSetChanged();
	}
	
	/**
	 * Xoa cac bien su dung: ViewHolder...
	 */
	public void clearTemporarity() {
		if (arrViewHolder != null)
			arrViewHolder.clear();
//		arrViewHolder = null;
	}
	
	/**
	 * Cancel cac task load anh khi close fragment
	 */
	public void pauseLoadingImage() {
		if (arrViewHolder != null) {
			for (ViewHolder viewHolder : arrViewHolder) {
				try {
					if (viewHolder.image != null) {
						ImageWorker.cancelWork(viewHolder.image);
					}
				} catch (Exception e) {
				}
			}
		}
	}
	
	/**
	 * Clear memory cache
	 */
	public void clearMemoryCacheOnly() {
		Log.e("SongsAdapter", "clearMemoryCacheOnly");
//		imageFetcher.clearMemoryCacheOnly();
	}
	
	/**
	 * Goi ham nay khi Fragment chua no xay ra onDestroy
	 */
	public void destroyAdapter() {
		clear();
		listData = null;
		listArticle = null;
		arrViewHolder = null;
//		imageFetcher = null;
	}
	
	// ======================== GOI API TUONG UNG VOI CAC ADAPTER ==========================
	
	/**
	 * List Content Update
	 */
	private void requestAPI(int page, ResponseListener responseListener) {
		ApiController.getUpdate(parentFragment.getActivity(),
				page, ConfigUtility.PAGE_SIZE, responseListener);
	}
	
	private void getData(final int page) {
		
		ResponseListener responseListener = new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				notifyNoMorePages();
				isLoadingMore = false;
			}
			
			@Override
			public void processResponse(String response) {
				if (response != null) {
					try {
						ArrayList<UpdateEntity> list = ParseJSON.getAllUpdateObjectFromResponse(response);
						if (list != null && list.isEmpty() == false) {
							listData.addAll(list);
							filterArticle();
							//===== Tao Mang ViewHolder=====
							for (int i = 0; i < list.size(); i++) {
								arrViewHolder.add(null);
							}
							//==============================
							nextPage();
							notifyDataSetChanged();
							if (list.size() < ConfigUtility.PAGE_SIZE)
								notifyNoMorePages();
							else
								notifyMayHaveMorePages();
						} else {
							notifyNoMorePages();
						}
					} catch (Exception e) {
						notifyNoMorePages();
					} finally {
						isLoadingMore = false;
					}
				} else {
					notifyNoMorePages();
				}
				
			}
		};
		
		requestAPI(page, responseListener);
	}
	
	private void getFirstPage() {
		int page = 1;
		ResponseListener responseListener = new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				notifyNoMorePages();
			}
			
			@Override
			public void processResponse(String response) {
				if (response != null) {
					ArrayList<UpdateEntity> list = ParseJSON.getAllUpdateObjectFromResponse(response);
					if (list != null && list.isEmpty() == false) {
						notifyMayHaveMorePages();
						
						resetList(list);
						filterArticle();
					} else {
						notifyNoMorePages();
					}
				} else {
					notifyNoMorePages();
				}
			}
		};

		requestAPI(page, responseListener);
	}

	private void filterArticle() {
		if (listArticle == null) {
			listArticle = new ArrayList<ArticleEntity>();
		}
		
		listArticle.clear();
		if (listData != null) {
			for (int i = 0; i < listData.size(); i++) {
				UpdateEntity updateItem = getItem(i);
				int itemType = updateItem.getFreeType();
				if ( itemType == updateItem.FREE_TYPE_NEWS  ||
						itemType == updateItem.FREE_TYPE_STORY ||
						itemType == updateItem.FREE_TYPE_EVENT    ) {
					listArticle.add(updateItem.getArticleEntity());
				}
			}
		}
	}

	public void onItemClick(int position) {
		if (getCount() == 0) return;
		UpdateEntity itemClick = getItem(position);
		int itemType = itemClick.getFreeType();
		if (itemType == itemClick.FREE_TYPE_ALBUM) {
			AlbumEntity currentItem = itemClick.getAlbumEntity();
			mainActivity.openDetailAlbum(currentItem);
		} else if (itemType == itemClick.FREE_TYPE_VIDEO) {
			VideoEntity currentItem = itemClick.getVideoEntity();
			mainActivity.openDetailVideo(currentItem);
		} else if ( itemType == itemClick.FREE_TYPE_NEWS  ||
				itemType == itemClick.FREE_TYPE_STORY ||
				itemType == itemClick.FREE_TYPE_EVENT    ) {
			mainActivity.openDetailArticle(listArticle, itemType, position);
		}
	}
}
